<!-- 低代码 主页面：用于展示列表页 -->
<template>

	<view class="lowcode-nav-wrap">
		<eui-nav-bar :title="lowcodePage?.c_name || ''" color="#333" />
		<eui-search-bar v-if="lowcodePage?.Search?.SearchItems?.length" ref="searcBarRef" radius="100" showFilter
			placeholder="请输入搜索内容" @clear="handleClearSearch" @confirm="handleEnterSearch">
			<template #searchFields>
				<view class="lowcode-components-wrap">
					<view v-for="(colField, idx) in lowcodePage?.Search?.SearchItems" :key="idx"
						class="lowcode-components-item">
						<DynamicComponent :conf-object="colField" :data-object="state.searchCardData" parentSrc="1"
							@handleDynamicChange="handleSearchDynamicChange" :md-code="state.mdCode || ''" />
					</view>
				</view>
				<view class="lowcode-popup-bottom flex-1 flex">
					<eui-button type="max2" title="重置" singleTag="重置" @buttonClick="handlePopupClose"></eui-button>
					<eui-button type="max" title="确认" singleTag="确认" @buttonClick="handlePopupClose"></eui-button>
				</view>
			</template>
		</eui-search-bar>
	</view>
	<scroll-view scroll-y :refresher-enabled='true' :refresher-triggered="scrollTriggerd"
		@refresherrefresh="handleScrollRefresh" @scrolltolower="handleScrolltolower" :style="getScrollViewStyle()">
		<view class="lowcode-edit-wrap lowcode-maintain-edit-wrap">
			<eui-card v-for="(rowData, rowIdx) in state.ListData" :key="rowIdx" title="" hPadding="28" type="single">
				<!-- <eui-card v-if="state.ListData?.length" class="lowcode-bill-detail-edit-card-wrap" hPadding="28" type="single"> -->
				<view class="lowcode-page-card-chead-wrap">
					<eui-row v-for="(rowCols, fIdx) in state?.ComponentsHeader" :key="fIdx"
						v-if="state?.ComponentsHeader?.length" class="lowcode-page-row-wrap">
						<eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col"
							:span="colField?.c_col_span || 12">
							<view class="lowcode-item-detail-view">
								<text
									class="lowcode-card-title item-text item-text-detail">{{ getDetailCardTitle(rowData, colField) }}</text>
							</view>
						</eui-col>
					</eui-row>
					<eui-row v-if="state?.ComponentsHeader?.length===0" class="lowcode-page-row-wrap">
						<view class="edit-page-tb-row-title-txt">第{{ (+rowIdx || 0) + 1 }}行</view>
					</eui-row>
					<view class="lowcode-page-card-chead-op-icons">
						<eui-uicons v-if="state.menusCFG?.some?.(m => m.menuCode === 'DeleteRow')"
							:disabled="mBtnDis({menuCode:'DeleteRow'})" color="#888888" type="trash" size="30"
							@click="handleDelRow(rowData, +rowIdx)" />
						<eui-uicons v-if="state.menusCFG?.some?.(m => m.menuCode === 'AddRow')" color="#888888"
							style="margin-left: 32rpx;" type="compose" size="30" :disabled="mBtnDis({menuCode:'Edit'})"
							@click="handleEditRow(rowData, +rowIdx)" />
					</view>
				</view>
				<view class="lowcode-title-line" />
				<view class="lowcode-edit-page-tb-row-wrap" :key="rowIdx">
					<view class="lowcode-page-card-cnt" v-if="state?.listColumns?.length">
						<eui-row v-for="(rowCols, fIdx) in state?.listColumns" :key="fIdx"
							class="lowcode-page-row-wrap">
							<eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col"
								:span="colField?.c_col_span || 12">
								<eui-text v-if="colField?.c_type !== 'fileupload'" cWidth="width: 100%"
									v-bind="state.cellProps?.[rowIdx+'_'+fIdx+'_'+cfIdx]" />
								<UploadFile v-else-if="colField?.c_type === 'fileupload'" :readonly="true"
									:autoUpload="false" serviceName="EnjoyMain" fileMediatype="image"
									:fileId="rowData?.[colField?.c_code || '']" fileClass="lowcode" return-type="array"
									mode="grid" :imageStyles="{ width:74,height:74 }"
									:customFetchUniqueKey="LOWCODERUNTIMEUNIQUEKEY"
									customFetchMethodName="FetchLowcodeFile" />
							</eui-col>
						</eui-row>
						<view class="lowcode-page-sub-card-panel" v-for="(Panel1, pIdx) in state.Panels">
							<view class="lowcode-page-card-chead-wrap" v-if="Panel1?.c_name">
								<text class="lowcode-card-title item-text item-text-detail">{{ Panel1?.c_name }}</text>
							</view>
							<view class="lowcode-title-line" v-if="Panel1?.c_name" />
							<view class="lowcode-page-sub-card-cnt" v-if="Panel1?.Components?.length">
								<eui-row v-for="(rowCols1, fIdx) in Panel1?.Components" :key="fIdx"
									class="lowcode-page-row-wrap">
									<eui-col v-for="(colField1, cfIdx) in rowCols1" :key="cfIdx"
										class="lowcode-page-col" :span="colField1?.c_col_span! || 6">
										<eui-text v-if="colField1?.c_type !== 'fileupload'" cWidth="width: 100%"
											v-bind="state.subCellProps?.['main_sub'+(Panel1?.c_guid || '')+rowIdx+'_'+fIdx+'_'+cfIdx]" />
										<UploadFile v-else-if="colField1?.c_type === 'fileupload'" :readonly="true"
											:autoUpload="false" serviceName="EnjoyMain" fileMediatype="image"
											:fileId="rowData?.[colField1.c_code || '']" fileClass="lowcode"
											return-type="array" mode="grid" :imageStyles="{ width:74,height:74 }"
											:customFetchUniqueKey="LOWCODERUNTIMEUNIQUEKEY"
											customFetchMethodName="FetchLowcodeFile" />
									</eui-col>
								</eui-row>
							</view>
						</view>
					</view>
				</view>
			</eui-card>
		</view>
	</scroll-view>

	<view class="lowcode-page-btm-btns-wrap">
		<eui-button v-for="(mCFG, mIdx) in state.menusCFGBottom" :key="mIdx" :type="getMenuBtnType(mCFG, mIdx)"
			:title="mCFG.menuTitle" :singleTag="mCFG.menuCode" :disabled="mBtnDis(mCFG)" @buttonClick="handleBtnClick"
			class="lowcode-page-btm-btn" />
	</view>
	<eui-popup ref="popupRef" class="lowcode-create-popup-wrap" background-color="#f8f8f8" type="bottom"
		:mask-click="false">
		<view class="lowcode-popup-content" :style="state.createPopupStyle">
			<view class="lowcode-popup-title">
				<view class="lowcode-popup-title-txt">{{ state.editTbIdx === undefined ? "新增行" : "修改行" }}</view>
				<view class="lowcode-popup-cancel" @tap="handleDetailPopupClose">
					<eui-uicons type="closeempty" size="40" color="#888888" />
				</view>
			</view>
			<scroll-view scroll-y class="lowcode-popup-default-content">
				<view v-for="(colField, idx) in state.showComponentsEdit" :key="idx" class="lowcode-components-item">
					<DynamicComponent :conf-object="colField" :data-object="state.popupData"
						@handleDynamicChange="handlePopDynamicChange" parentSrc="3"
						:md-code="props?.mdInfo?.c_mdcode" />
				</view>
			</scroll-view>
		</view>
		<view class="lowcode-popup-bottom flex-1 flex">
			<eui-button type="max2" title="重置" singleTag="重置" @buttonClick="handleDetailPopupClose"></eui-button>
			<eui-button type="max" title="确认" singleTag="确认" @buttonClick="handleDetailPopupClose"></eui-button>
		</view>
	</eui-popup>
</template>

<script setup lang="ts">
	import { ref, watch } from "vue";
	import store from '@/store';
	import useService from "@/hooks/useService";
	import { onLoad, onReady, onShow } from "@dcloudio/uni-app";
	import { initRdsDict, getRdsSysConfig } from '@/hooks/init';

	import DynamicComponent from "../dynamicComponent/index.vue";
	import UploadFile from "@/components/UploadFile.vue";

	import type { LowCodePagination, LowCodeWhereListItem, LowcodeBtnEvent, LowcodeGridRowColComponents, LowcodeMdInfo, LowcodeMenuItemCFG, LowcodePage, LowcodePagePanel, LowcodePagePanelComponentItem, LowcodeRect } from "../interface";
	import type { MaintainState, FetchMaintainDataProxy, FetchMaintainResult, FetchMaintainParam } from "./interface";
	import { LOWCODERUNTIMEUNIQUEKEY, lowcodeRowKey } from "../constant";
	import { formGridSort, setLowcodeRowKey } from "../utils";

	import useLowcodeValidator from "../hooks/useLowcodeValidator";
	import useLowcodeDataEvent from "../hooks/useLowcodeDataEvent";
	import useLowcodeSystemInfo from "../hooks/useSystemInfo";
	import useLowcodeDef from "../hooks/useLowcodeDef";
	import useComponentProps from "../hooks/useComponentProps";
	import useLowcodeMenuBtns from "../hooks/useLowcodeMenuBtns";

	const props = defineProps<{ lowcodePage : LowcodePage; detailMdCode : string; mdInfo : LowcodeMdInfo }>();
	const pagination = ref<LowCodePagination>({ CurrentPage: 1, RowsCount: 0, PageCount: 1, fetchCount: 0 });
	const state = ref<MaintainState>({
		ListData: [], listColumns: [], menusCFG: [], menusCFGBottom: [], searchCardData: {},
		Panel: {}, Panels: [],
		popupData: {}, validateErrorDataPop: {}, cellProps: {},
		tableSaveData: { DelList: [], NewList: [], ModifiedList: [], tableName: '', primaryKeys: [] },
		initOtherPanelDataObj: {}, componentConf: {}, createPopupStyle: {}
	});

	const service = useService({ prefix: "mainApi" });

	const scrollTriggerd = ref<boolean>(false);
	const searcBarRef = ref<{ closeDrawer ?: () => void } | null>(null);
	const popupRef = ref();

	const { getSystemInfo } = useLowcodeSystemInfo();
	const { getComponentProps } = useComponentProps();

	const { generateLowcodeDef } = useLowcodeDef({ mdCode: props?.mdInfo?.c_mdcode });
	const { handleValidator } = useLowcodeValidator({ mdCode: props?.mdInfo?.c_mdcode });
	const { handleEventData } = useLowcodeDataEvent({ mdCode: props?.mdInfo?.c_mdcode });
	const { handleSaveList } = useLowcodeMenuBtns();
	//
	const getDetailCardTitle = (rowData : any, colField : LowcodePagePanelComponentItem) => {
		const rawIdVal = rowData?.[colField?.c_code || ""];
		if (colField?.c_displayname_code) {
			const rawIdNameVal = rowData?.[colField?.c_displayname_code] || "";
			return rawIdVal ? `[${rawIdVal}]${rawIdNameVal || ""}` : rawIdVal;
		}
		return rawIdVal;
	};

	const getScrollViewStyle = () => {
		const sysH = Math.ceil(state.value?.systemInfo?.windowHeight || 0);
		const navWrapH = Math.ceil(state.value?.navWrapRect?.height || 0);
		const scrollH = (sysH >= navWrapH) ? (sysH - navWrapH) : 0;
		return {
			"background-color": "#f2f2f2",
			width: state.value?.systemInfo?.windowWidth + 'px',
			height: (scrollH - 60) + 'px',
			"padding-bottom": '10px'
		};
	};

	const getMenuBtnType = (mCFG : LowcodeMenuItemCFG, mIdx : number) => {
		if (mIdx + 1 === state.value?.menusCFGBottom?.length) {
			return "min";
		}
		return "min2";
	};


	const handleScrollRefresh = () => {
		if (!scrollTriggerd) {
			return;
		}
		scrollTriggerd.value = true;
		pagination.value = { CurrentPage: 1, RowsCount: 0, PageCount: 1, fetchCount: 0 };
		fetchMdListData();
	};

	const handleScrolltolower = () => {
		if ((pagination?.value?.CurrentPage || 0) >= (pagination?.value?.PageCount || 0)) {
			return
		}
		pagination.value.CurrentPage = (pagination?.value?.CurrentPage || 1) + 1;
		fetchMdListData();
	};

	const mBtnDis = (mCFG : LowcodeMenuItemCFG) => {
		let btnDis = false; // TODO 新建和审批，权限码里不包含这两个，要不要根据权限码判断禁用
		const mdLimit = props?.mdInfo?.c_limitcode || "R";	// c_limitcode: "RWSAOICUXDBP"

		if (mCFG.menuCode === "SaveBill" && !mdLimit.includes("W")) {
			btnDis = true; 	// 保存
		}

		if (mCFG.menuCode === "AddRow" && !mdLimit.includes("W")) {
			btnDis = true; 	// 新的
		}

		if (mCFG.menuCode === "Edit" && !mdLimit.includes("W")) {
			btnDis = true;
		}

		if (mCFG.menuCode === "DeleteRow" && !mdLimit.includes("W")) {
			btnDis = true;
		}
		return btnDis;
	};

	// 按键
	const handleBtnClick = async (btnEvent ?: LowcodeBtnEvent) => {
		if (btnEvent?.singleTag === "AddRow") {
			await handleAddRow();
			return;
		}
		if (btnEvent?.singleTag === "SaveBill") {
			await handleSave()
			return;
		}
	};
	// 
	const hasFieldChanged = () => {
		const { tableSaveData } = state.value || {};
		let isChanged = false;

		if (tableSaveData) {
			const { NewList, ModifiedList, DelList } = tableSaveData;
			isChanged = (NewList || []).length + (ModifiedList || []).length + (DelList || []).length > 0
		}

		return isChanged;
	};

	// 保存
	const handleSave = async () => {
		const { tableSaveData, Panel } = state.value || {};
		const hasFieldChangedRes = hasFieldChanged();
		console.log("SaveBill-state.tableSaveData", state.value.tableSaveData);
		if (!hasFieldChangedRes) {
			uni.showModal({ title: "提示", content: "没有任何修改，不需要保存", showCancel: false, success: (res) => { } });
			return;
		}

		if (Object.keys(state.value.validateErrorDataPop || {})?.length) {
			// TODO 保存前的校验，提示，交互定位 现有组件无法定位
			uni.showModal({ title: "提示", content: "有不合法字段，请修改后再提交！", showCancel: false, success: (res) => { } });
			return;
		}

		const { NewList, ModifiedList, DelList } = tableSaveData;
		const saveRes = await handleSaveList({
			ModuleCode: props?.lowcodePage?.c_lowcode_guid!,
			tableName: Panel?.PanelEditTableName!,
			primaryKeys: Panel?.PrimaryKeys!,
			NewList: NewList,
			ModifiedList: ModifiedList,
			DelList: DelList,
		});

		if (saveRes) {
			state.value.tableSaveData = {
				...state.value.tableSaveData,
				NewList: [],
				ModifiedList: [],
				DelList: []
			};
		}

		return saveRes;
	}

	// 新增
	const handleAddRow = async () => {
		const panelData = state.value.ListData;
		const newRow = await generateLowcodeDef({ Components: state.value.showComponentsEdit, editTbName: state.value.Panel?.PanelEditTableName, panelData });
		const __keyMax = Array.isArray(panelData) && panelData?.length ? Math.max(...panelData?.map(r => r?.[lowcodeRowKey])) : 0;
		const defNewRow = { ...newRow, [lowcodeRowKey]: __keyMax + 1 };
		state.value.popupData = { ...defNewRow };
		state.value.editTbRowData = { ...defNewRow };
		popupRef.value?.open();
	};

	// 删除
	const handleDelRow = async (delData ?: { [key : string] : any }, rowIdx ?: number) => {
		const modalCnt = `您确认要删除当前行吗？`;	 // 删除行
		uni.showModal({
			title: "提示", content: modalCnt, success: async (res) => {
				if (res.confirm) {
					if (delData?.[lowcodeRowKey] >= 0) {
						const { tableSaveData } = state.value;
						const { NewList } = tableSaveData;

						const isNew = NewList.findIndex(f => { return f[lowcodeRowKey] == delData?.[lowcodeRowKey] }) >= 0;
						if (isNew) {
							state.value.tableSaveData.NewList = NewList.filter(f => {
								return f[lowcodeRowKey] != delData?.[lowcodeRowKey]
							});
						} else {
							state.value.tableSaveData.DelList.push(delData);
						}

					}

					const newListData : any = [];
					state.value.ListData?.forEach((r : any, i : number) => i !== rowIdx && newListData.push(r));
					state.value.ListData = newListData;
					await getCellProps();
				}
			}
		});
	};

	// 编辑
	const handleEditRow = async (rowData ?: { [key : string] : any }, rowIdx ?: number) => {
		state.value.popupData = { ...rowData };
		state.value.editTbRowData = { ...rowData };
		state.value.editTbIdx = rowData?.[lowcodeRowKey];
		popupRef.value?.open();
	};


	const handlePopDynamicChange = async (key : string, newVal : any, oldVal : any, proxy ?: { [key : string] : any }) => {
		if (!state.value.popupData) {
			state.value.popupData = {};
		}

		state.value.popupData[key] = newVal;
		const mergeFieldAry = Object.keys(proxy?.mergeFields || {});
		if (mergeFieldAry?.length) {
			mergeFieldAry?.map(fk => (state.value.popupData![fk] = proxy?.mergeFields?.[fk]));
		}

		const fieldConf = state.value.componentConf?.[key] || {};
		const valType = fieldConf?.c_type === "numberinput" ? "number" : "string";
		// const validateItems = fieldConf?.c_datavalidate?.validateItems;
		const validateRes = await handleValidator({ value: newVal, valType, fieldConf, rowData: { ...state.value.popupData } }) as { validated ?: boolean, msg ?: string };
		if (validateRes && !validateRes?.validated) {
			uni.showModal({ title: "提示", content: validateRes?.msg, showCancel: false, success: () => { } });
			state.value.validateErrorDataPop![key] = { oldVal: "", newVal: newVal, msg: validateRes?.msg };
			return;
		}
		delete state.value.validateErrorDataPop![key];

		const newRecord = await handleEventData({ record: { ...state.value.popupData }, fieldName: key, newValue: newVal, itemsConfig: state.value?.Panel?.Components });
		Object.keys(newRecord || {}).map(k => state.value.popupData![k] = (newRecord as any)[k]);
	};

	// 生成内容数据
	const getCellProps = async () => {
		if (!state.value?.ListData || !state.value?.showComponents?.length) {
			return;
		}

		for (let idx = 0; idx < state.value?.ListData?.length; idx++) {
			const rowData = state.value?.ListData[idx];

			for (let fIdx = 0; fIdx < state.value?.listColumns!.length; fIdx++) {
				const rowCols = state.value?.listColumns![fIdx];
				for (let cfIdx = 0; cfIdx < rowCols?.length; cfIdx++) {
					if (!state.value?.cellProps) {
						state.value.cellProps = {};
					}
					const colField = rowCols[cfIdx];
					state.value.cellProps[idx + '_' + fIdx + '_' + cfIdx] = await getComponentProps({ componentType: 'EuiText', confObject: colField, dataObject: rowData, parentSrc: "3" });
				}
			}

			await getSubCardCellProps(idx, rowData);
		}

		// console.log("state.value.cellProps ", state.value.cellProps);
		// console.log("state.value.subCellProps ", state.value.subCellProps);
	};

	// 设置子卡片
	const getSubCardCellProps = async (idx : number, rowData : { [key : string] : any; }) => {
		const mainSubCardFormPanels = state.value?.Panels;
		for (let i = 0; i < (mainSubCardFormPanels?.length || 0); i++) {
			const mainSubCardFormPanel = mainSubCardFormPanels?.[i] as LowcodeGridRowColComponents;
			const subKey = "main_sub" + (mainSubCardFormPanel?.c_guid || "") + idx + '_';

			await fillSubCellProps(subKey, mainSubCardFormPanel, rowData);
		}
	};

	// 设置子卡片数据
	const fillSubCellProps = async (subKey : string, subCardFormPanel ?: LowcodeGridRowColComponents, formData ?: { [key : string] : any }, parentSrc ?: string) => {
		if (!formData || !subCardFormPanel?.Components?.length) {
			return;
		}
		for (let fIdx = 0; fIdx < subCardFormPanel?.Components?.length; fIdx++) {
			const rowCols = subCardFormPanel?.Components[fIdx];
			for (let cfIdx = 0; cfIdx < rowCols?.length; cfIdx++) {
				if (!state.value?.subCellProps) {
					state.value.subCellProps = {};
				}
				const colField = rowCols[cfIdx];
				state.value.subCellProps[subKey + fIdx + '_' + cfIdx] = await getComponentProps({ componentType: 'EuiText', confObject: colField, dataObject: formData, parentSrc });
			}
		}
	}

	// 新增行 修改行 事件
	const handleDetailPopupClose = async ({ singleTag } : { singleTag : string }) => {
		// console.log("handlePopupClose popupData ", state.value.popupData);
		if (singleTag === "重置") {
			Object.keys(state.value.popupData || {})?.forEach(k => {
				state.value.popupData![k]! = state.value.editTbRowData![k];
			});
			state.value.validateErrorDataPop = {};
			return;
		}

		if (singleTag === "确认") {
			const allTbRequiredAry = state.value?.Panel?.Components?.filter?.(x => x?.c_hide !== "1" && x?.c_required === "1") || [];
			const allTbRequired = !allTbRequiredAry?.length || allTbRequiredAry?.every(f => (state.value.popupData?.[f?.c_code || ""] || (state.value.popupData?.[f?.c_code || ""] === 0)));
			if (!allTbRequired) {
				uni.showModal({ title: "提示", content: "有必填项未填写！", showCancel: false, success: (res) => { } });
				return;
			}

			if (Object.keys(state.value.validateErrorDataPop || {})?.length) {
				// TODO 保存前的校验，提示，定位 现有组件无法定位 + 处理必填
				uni.showModal({ title: "提示", content: "有不合法字段，请修改后再提交！", showCancel: false, success: (res) => { } });
				return;
			}

			if (!state.value.initOtherPanelDataObj) {
				state.value.initOtherPanelDataObj = {};
			}

			if (+(state.value.editTbIdx || "") === state.value.editTbIdx) {
				const { editTbIdx, tableSaveData } = state.value;
				const index = state.value.ListData?.findIndex(f => f[lowcodeRowKey] == editTbIdx) || editTbIdx;
				state.value.ListData?.splice(index, 1);
				state.value.ListData?.splice(index, 0, { ...state.value.popupData });


				const { ModifiedList, NewList } = tableSaveData;
				const modIndex = ModifiedList.findIndex(f => f[lowcodeRowKey] == editTbIdx);
				if (modIndex >= 0) {
					state.value.tableSaveData.ModifiedList?.splice(modIndex, 1);
					state.value.tableSaveData.ModifiedList?.splice(modIndex, 0, { ...state.value.popupData });
				} else {
					const newIndex = NewList.findIndex(f => f[lowcodeRowKey] == editTbIdx);
					if (newIndex >= 0) {
						state.value.tableSaveData.NewList?.splice(newIndex, 1);
						state.value.tableSaveData.NewList?.splice(newIndex, 0, { ...state.value.popupData });
					} else {
						state.value.tableSaveData.ModifiedList.push({ ...state.value.popupData });
					}
				}
			} else {
				state.value.ListData?.push({ ...state.value.popupData });
				state.value.tableSaveData.NewList.push({ ...state.value.popupData });
			}

			await getCellProps();
			state.value.editTbIdx = undefined;
			state.value.editTbRowData = {};
		}
		state.value.validateErrorDataPop = {};
		popupRef.value?.close();
	};
	// 修改查询项
	const generateWhere = () => {
		let newWhereList : LowCodeWhereListItem[] = [];
		const searchVal = state.value.fuzzyVal;
		const fuzzyFields = props?.lowcodePage?.Search?.c_fuzzyquery?.split(",");
		Array.isArray(fuzzyFields) && searchVal && fuzzyFields?.forEach((fk, idx) => {
			newWhereList.push({ c_left: idx === 0 ? "(" : "", c_col: fk, c_oper: "相似", c_value: searchVal, c_col_dtype: "System.String", c_logic: "或者", c_right: (idx + 1) === fuzzyFields.length ? ")" : "" });
		});

		Array.isArray(props?.lowcodePage?.Search?.SearchItems) && props?.lowcodePage?.Search?.SearchItems?.forEach(item => {
			const iVal = state.value.searchCardData?.[item.c_code || ""] || "";
			iVal && newWhereList.push({ c_left: "", c_col: item.c_code, c_oper: "相似", c_value: iVal, c_col_dtype: "System.String", c_logic: "而且", c_right: "" });
		});
		state.value.whereList = newWhereList;
		pagination.value = { CurrentPage: 1, RowsCount: 0, PageCount: 1, fetchCount: 0 };
		uni.showLoading({ title: "查询中...", mask: true });
	};
	// 查询项
	const handlePopupClose = ({ singleTag } : { singleTag : string }) => {
		if (singleTag === "重置") {
			if (!state.value.searchCardData) {
				state.value.searchCardData = {};
			}
			Array.isArray(props?.lowcodePage?.Search?.SearchItems) && props?.lowcodePage?.Search?.SearchItems?.forEach(item => state.value.searchCardData![item.c_code || ""] = "");
		}
		if (singleTag === "确认") {
			generateWhere();
			fetchMdListData();
			searcBarRef.value?.closeDrawer?.();
		}
	};

	// 清除搜索框
	const handleClearSearch = () => {
		state.value.fuzzyVal = "";
		generateWhere();
		fetchMdListData();
	};
	// 查询
	const handleEnterSearch = (proxy ?: { value ?: string }) => {
		const searchVal = proxy?.value || "";
		state.value.fuzzyVal = searchVal;
		generateWhere();
		fetchMdListData();
	};
	// 修改查询值
	const handleSearchDynamicChange = async (key : string, newVal : any, oldVal : any, proxy ?: { [key : string] : any }) => {
		if (!state.value.searchCardData) {
			state.value.searchCardData = {};
		}

		state.value.searchCardData[key] = newVal;
	};


	// 查询数据
	const fetchMdListData = async (fetchProxy ?: FetchMaintainDataProxy) => {
		uni.showLoading({ title: "查询中...", mask: true });
		const basicReq = {
			BillMode: 0,
			PageSize: 100,
			IsNotPage: false,
			AggregateList: [],
			WhereList: state.value?.whereList || []
		};
		const fetchReq = {
			...basicReq,
			CurrentPage: pagination.value.CurrentPage || 1,
		};
		const fetchReqProxy = {
			ModuleCode: state.value?.mdCode
		};

		const fetchRes = await service.request<FetchMaintainParam, FetchMaintainResult>(LOWCODERUNTIMEUNIQUEKEY, "EnjoyQueryList", fetchReq, "", "", fetchReqProxy);
		scrollTriggerd.value = false;
		if (!fetchRes) {
			uni.hideLoading();
			return;
		}
		const fetchResData = (fetchRes as FetchMaintainResult);
		const cacheReturnObject = (Array.isArray(fetchResData?.ReturnObject)
			? fetchResData?.ReturnObject?.map(r => ({ ...r }))
			: []);

		if (!pagination.value.fetchCount) {
			state.value.ListData = setLowcodeRowKey(cacheReturnObject);
			pagination.value = {
				...pagination.value,
				RowsCount: fetchResData?.RowsCount,
				PageCount: fetchResData?.PageCount,
				fetchCount: 1
			};
		} else {
			pagination.value.fetchCount = pagination.value.fetchCount + 1;
			state.value.ListData = setLowcodeRowKey((state.value.ListData || [])?.concat(cacheReturnObject));
		}

		await getCellProps();
		uni.hideLoading();

		if (fetchProxy?.isOnLoad) {
			const userInfoPage = uni.createSelectorQuery().select(".lowcode-nav-wrap");
			userInfoPage.boundingClientRect(rect => {
				state.value.navWrapRect = (rect as LowcodeRect);

				const basicPageH = Math.floor(state.value.systemInfo?.windowHeight - (state.value?.navWrapRect?.height || 0) - 120);
				const height = Math.floor(basicPageH * 0.9) + "px";

				state.value.createPopupStyle = { height: height };
			}).exec();
		}
	};
	// 展示界面
	const handleLowCodePage = async () => {
		const lowcodePage = props?.lowcodePage;
		state.value.detailMdCode = props?.detailMdCode || "";
		state.value.mdCode = lowcodePage?.c_lowcode_guid || "";

		const menuCFG = lowcodePage?.c_menuCFG || null;
		if (menuCFG && Array.isArray(menuCFG.menus) && menuCFG.menus.length) {
			state.value.menusCFG = menuCFG.menus;
			state.value.menusCFGBottom = menuCFG.menus.filter(f => f.menuCode !== "DeleteRow");
		}

		const Panel = lowcodePage?.Panels?.find(f => ['', null, undefined].includes(f.c_ppanel_guid));
		state.value.Panel = Panel!;
		const showComponents = (Panel || {})?.Components?.filter(f => f.c_hide !== '1');
		state.value.showComponents = showComponents!;

		const Panels = (lowcodePage?.Panels?.filter(f => f.c_ppanel_guid === Panel?.c_guid) || [])
			?.sort((a, b) => (a as any)?.c_row_index - (b as any)?.c_row_index);
		state.value.Panels = (Panels || []).map(m => {
			return { ...m, Components: formGridSort((m.Components || [])?.filter(c => !["fileupload"].includes(c.c_type || "")), { excludeFields: [] })?.Components }
		}) as LowcodePagePanel[];

		const showComponentsEdit = (Panels || {})?.map(m => {
			return m.Components?.filter(f => f.c_hide !== '1' && (showComponents || [])?.findIndex(fi => fi.c_code == f.c_code) < 0)
		}).flatMap(f => f).filter(Boolean) as LowcodePagePanelComponentItem[];

		console.log('showComponentsEdit', showComponentsEdit)
		state.value.showComponentsEdit! = showComponents?.concat(showComponentsEdit || [])!;

		// const showComponents = (showComponentsPanel || []).concat(showComponentsPanels || [])


		// 列表页 的 ComponentsHeader 写死，用c_is和c_status &&  列表页不显示上传图片和上传文件
		state.value.listColumns = formGridSort(showComponents?.filter(c => !["fileupload"].includes(c.c_type || "")), { excludeFields: [] })?.Components;
		state.value.ComponentsHeader = formGridSort(showComponents?.filter(c => !["fileupload"].includes(c.c_type || "")), { excludeFields: [] })?.ComponentsHeade;

		state.value.componentConf = Panel?.Components
			?.reduce((obj, item) => ({ ...obj, [item?.c_code || ""]: item }), {}) as { [key : string] : LowcodePagePanelComponentItem };
	};
	// 查询系统参数
	const handleSystemInfo = () => {
		const systemInfo = getSystemInfo();
		state.value.systemInfo = systemInfo;
	};

	// 初始化
	onLoad(async (proxy) => {
		console.log("onLoad proxy ", props);

		uni.$on("RefreshPage", fetchMdListData);
		await initRdsDict();
		handleSystemInfo();
		await handleLowCodePage();
		fetchMdListData({ isOnLoad: true });
	});
</script>

<style scoped lang="scss">
	@import '@/main.scss';
	@import "../index.scss";
	@import "./index.scss";
</style>